package com.su.gulimall.seckill.schedule;

import com.su.gulimall.seckill.service.SecKillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

//商品定时上架功能：每天凌晨3点钟进行上架最近三天需要秒杀的商品
@Service
@Slf4j
public class SeckillSkuScheduled {
    @Autowired
    SecKillService secKillService;
    @Autowired
    RedissonClient redissonClient;
    private final String upload_lock="seckill:upload:lock";
    //TODO:上架过的数据不需要重复上架；
    @Scheduled(cron = "* * 10 * * ?")
    public void uploadSecKillSku() {
        log.info("秒杀活动开始，正在上架秒杀商品");
        //分布式锁，获取到锁的人执行
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            //秒杀商品的上架
            secKillService.uploadSecKillSku();
        }finally {
            //无论抢占到锁的线程是否执行成功，到时间都要对锁进行释放，
            //但是看门狗会自动续期啊；
            //这个逻辑有问题；
            lock.unlock();
        }
    }
}
